<template>
  <div>
    <!-- 表单弹窗 -->
    <el-dialog
      class="el-dialog__wrapper avue-dialog avue-crud__dialog"
      :title="dialogText"
      :visible.sync="dialogVisible"
      append-to-body
      :close-on-click-modal="false"
      :before-close="handleClose"
      width="70%"
    >
      <el-form
        ref="form"
        :model="reprecForm"
        :rules="rules"
        label-width="100px"
      >
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="分账模式" prop="divisionPattern">
              <select-dict
                ref="divisionPattern"
                :select.sync="reprecForm.divisionPattern"
                code="division_pattern_hand"
                placeholder-text="分账模式"
                :disabled="true"
                @change="handleDpChange"
              ></select-dict>
            </el-form-item>
          </el-col>
          <el-col :span="8" v-if="reprecForm.divisionPattern == 1">
            <el-form-item label="退款金额" prop="refundAmount">
              <el-input
                type="number"
                oninput="if(value){value=value.replace(/[^\d]/g,1);if(Number(value)<=0){value=0}} if(Number(value)>parseFloat(refundAmount)){value=parseFloat(refundAmount)}"
                size="mini"
                class="haruyuki-width-100"
                :placeholder="'退款金额不能超过' + refundAmount + '元'"
                v-model="reprecForm.refundAmount"
                @blur="handleRefundAmount"
              >
                <span slot="suffix">元</span>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <div class="alter-basic" v-if="reprefdInfo.k2.length > 0">
          <div class="row-alter alter-width-4x">
            <div class="col-alter border-bottom">
              <span class="alter-title">退款对象</span>
            </div>
            <div
              class="col-alter"
              v-for="(k1Item, k1i) in reprefdInfo.k1"
              :key="k1i"
            >
              {{ k1Item == 1 ? "分账方" : "接收方" }}
            </div>
          </div>
          <div class="row-alter alter-width-4x">
            <div class="col-alter border-bottom">
              <span class="alter-title">分账接收方编号</span>
            </div>
            <div
              class="col-alter"
              v-for="(k2Item, k2i) in reprefdInfo.k2"
              :key="k2i"
            >
              {{ k2Item }}
            </div>
          </div>
          <div class="row-alter alter-width-4x">
            <div class="col-alter border-bottom">
              <span class="alter-title">分账接收方名称</span>
            </div>
            <div
              class="col-alter"
              v-for="(k3Item, k3i) in reprefdInfo.k3"
              :key="k3i"
            >
              {{ k3Item }}
            </div>
          </div>
          <div class="row-alter alter-width-4x">
            <div class="col-alter border-bottom">
              <span class="alter-title">退款金额</span>
            </div>
            <div
              class="col-alter cols"
              v-for="(item, i) in reprecForm.divisionRateList"
              :key="i"
            >
              <el-form-item
                label=""
                label-width="0"
                :prop="'divisionRateList.' + i + '.value'"
                :rules="{
                  required: true,
                  message: '退款金额不能为空',
                  trigger: 'blur',
                }"
              >
                <el-input
                  type="number"
                  oninput="if(value){value=value.replace(/[^\d]/g,1);if(Number(value)<=0){value=0}}"
                  size="mini"
                  class="haruyuki-width-100"
                  :placeholder="'请输入退款金额'"
                  :disabled="reprecForm.divisionPattern == 1"
                  v-model="item.value"
                >
                  <span slot="suffix">元</span>
                </el-input>
              </el-form-item>
            </div>
          </div>
        </div>
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="备注:" prop="refundRemark">
              <el-input
                type="textarea"
                v-model="reprecForm.refundRemark"
                placeholder="请输入备注"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <span
        slot="footer"
        class="avue-dialog__footer avue-dialog__footer--right"
      >
        <el-button
          size="small"
          type="primary"
          v-preventClick
          @click="handleSubmit"
          >确 定</el-button
        >
        <el-button size="small" @click="dialogVisible = false">取 消</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {
  divRefundCalc,
  handDivRefund,
} from "@/api/rb-oem/separateMerchant/separate_merchant_store";
import selectPage from "@/components/select-page/select-page";
import selectDict from "@/components/select-dict/select-dict";
export default {
  props: {
    dialogVisible: {
      type: Boolean,
      default: false,
    },
    reprefdInfo: {
      type: Object,
      default: () => ({
        data: {},
        k1: [],
        k2: [],
        k3: [],
      }),
    },
    rptOrderCode: {
      type: [String],
      default: "",
    },
    refundAmount: {
      type: [Number, String],
      default: 0,
    },
  },
  data() {
    return {
      dialogType: "",
      dialogText: "分账退款",
      reprecForm: {
        rptOrderCode: "",
        divisionPattern: "",
        divisionRateList: [],
        refundList: [],
      },
      rules: {
        divisionPattern: [
          { required: true, message: "请选择分账模式", trigger: "change" },
        ],
        refundAmount: [
          { required: true, message: "请输入退款金额", trigger: "change" },
        ],
        refundRemark: [
          { required: true, message: "请输入备注", trigger: "change" },
        ],
      },
      dpDisabled: false,
      dialogChildVisible: false,
    };
  },
  watch: {
    "reprefdInfo.data": {
      handler(val) {
        if (val.rptOrderCode) {
          this.reprecForm.rptOrderCode = val.rptOrderCode;
          this.getDivRefundCalc(this.refundAmount);
        }
      },
      deep: true,
      immediate: false,
    },
  },
  components: {
    selectPage,
    selectDict,
  },
  methods: {
    handleDpChange(val) {
      if (val) {
        this.refreshReset();
      }
    },
    handleRefundAmount(val) {
      if (val) {
        this.refreshReset();
        this.getDivRefundCalc(this.reprecForm.refundAmount);
      }
    },
    getDivRefundCalc(val) {
      let params = {
        rptOrderCode: this.reprecForm.rptOrderCode,
        refundAmount: val,
      };
      this.reprecForm.divisionRateList = [];
      divRefundCalc(params).then((res) => {
        if (res.data.success) {
          this.reprecForm.divisionPattern = res.data.data.divisionPattern + "";
          for (const item of res.data.data.refundList) {
            this.reprefdInfo.k1.push(item.divisionUserType);
            this.reprefdInfo.k2.push(item.recRpiNo);
            this.reprefdInfo.k3.push(item.recRpiName);
            this.reprecForm.divisionRateList.push({
              value: item.refundAmount,
            });
          }
        }
      });
    },
    isSelectChange(val, i) {
      for (const item of this.reprecForm.isChargeList) {
        item.value = 0;
      }
      this.reprecForm.isChargeList[i].value = val;
    },
    handleSubmit() {
      const _this = this;
      _this.$refs.form.validate((valid) => {
        if (valid) {
          if (_this.reprecForm.divisionPattern == 1) {
            // 清空绑定列表
            _this.reprecForm.refundList = [];
            // 直接遍历分账接收方数组，将每个接收方与对应的分账比例关联
            for (let index = 0; index < _this.reprefdInfo.k2.length; index++) {
              _this.reprecForm.refundList.push({
                recRpiNo: _this.reprefdInfo.k2[index],
                divisionUserType: index === 0 ? 1 : 2, // 第一个为分账方，其余为接收方
                refundAmount: _this.reprecForm.divisionRateList[index].value,
              });
            }
            _this.$nextTick(() => {
              const loading = _this.$loading({
                lock: true,
                text: "提交中...",
                spinner: "el-icon-loading",
              });
              handDivRefund(_this.reprecForm)
                .then(() => {
                  _this.$message.success("操作成功");
                  _this.dialogVisible = false;
                  _this.refreshReset();
                  _this.refreshChange();
                })
                .finally(() => {
                  loading.close();
                });
            });
          } else if (_this.reprecForm.divisionPattern == 2) {
            {
              const divisionRateTotal =
                _this.reprecForm.divisionRateList.reduce(
                  (acc, curr) => Number(acc) + Number(curr.value),
                  0
                );
              if (divisionRateTotal > Number(_this.refundAmount)) {
                _this.$message.warning(
                  "您已超限退款，请输入的总和不高于" + _this.refundAmount + "元"
                );
                return;
              } else {
                // 清空绑定列表
                _this.reprecForm.refundList = [];
                // 直接遍历分账接收方数组，将每个接收方与对应的分账比例关联
                for (
                  let index = 0;
                  index < _this.reprefdInfo.k2.length;
                  index++
                ) {
                  _this.reprecForm.refundList.push({
                    recRpiNo: _this.reprefdInfo.k2[index],
                    divisionUserType: index === 0 ? 1 : 2, // 第一个为分账方，其余为接收方
                    refundAmount:
                      _this.reprecForm.divisionRateList[index].value,
                  });
                }
                _this.$nextTick(() => {
                  const loading = _this.$loading({
                    lock: true,
                    text: "提交中...",
                    spinner: "el-icon-loading",
                  });
                  handDivRefund(_this.reprecForm)
                    .then(() => {
                      _this.$message.success("操作成功");
                      _this.dialogVisible = false;
                      _this.refreshReset();
                      _this.refreshChange();
                    })
                    .finally(() => {
                      loading.close();
                    });
                });
              }
            }
          }
        }
      });
    },
    handleClose(done) {
      this.$refs.form.resetFields();
      this.refreshReset();
      done();
    },
    refreshReset() {
      this.reprefdInfo.k1 = [];
      this.reprefdInfo.k2 = [];
      this.reprefdInfo.k3 = [];
      this.reprefdInfo.k4 = [];
      this.reprecForm.divisionRateList = [];
      this.reprecForm.isChargeList = [];
    },
    handleChildSubmit() {
      // 如果已有分账接收方，需要过滤掉重复的
      if (this.reprefdInfo.k2.length > 0) {
        // 获取已存在的分账接收方编号
        const existingRpiNos = new Set(this.reprefdInfo.k2);

        // 过滤出不重复的分账接收方
        const newItems = list.filter((item) => !existingRpiNos.has(item.rpiNo));

        // 添加新的分账接收方
        for (const item of newItems) {
          this.reprefdInfo.k1.push(2);
          this.reprefdInfo.k2.push(item.rpiNo);
          this.reprefdInfo.k3.push(item.rpiName);
          this.reprefdInfo.k4.push(this.reprecForm.divisionPattern);
          this.reprecForm.divisionRateList.push({ value: null });
          this.reprecForm.isChargeList.push({ value: 0 });
        }
      } else {
        this.reprefdInfo.k1.push(1);
        this.reprefdInfo.k2.push(this.reprefdInfo.data.rpiNo);
        this.reprefdInfo.k3.push(this.reprefdInfo.data.rpiName);
        this.reprefdInfo.k4.push(this.reprecForm.divisionPattern);
        this.reprecForm.divisionRateList.push({ value: null });
        this.reprecForm.isChargeList.push({ value: 0 });
        // 如果没有已存在的分账接收方，直接添加所有选中的
        for (const item of list) {
          this.reprefdInfo.k1.push(2);
          this.reprefdInfo.k2.push(item.rpiNo);
          this.reprefdInfo.k3.push(item.rpiName);
          this.reprefdInfo.k4.push(this.reprecForm.divisionPattern);
          this.reprecForm.divisionRateList.push({ value: null });
          this.reprecForm.isChargeList.push({ value: 0 });
        }
      }

      this.$message({
        type: "success",
        message: "添加成功!",
      });
      this.dialogChildVisible = false;
    },
  },
};
</script>

<style lang="scss" scoped>
.alter-basic {
  display: grid;
  grid-template-columns: repeat(4, 25%);
  border: 1px solid #ebeef5;
  margin-bottom: 20px;

  .alter-title {
    font-weight: bold;
    color: rgba(0, 0, 0, 0.85);
  }
}

.row-alter {
  display: flex;
  flex-direction: column;
  &.alter-width-4x {
  }
  &:nth-child(n + 2) {
    border-left: 1px solid #ebeef5;
  }
}

.col-alter {
  padding-left: 10px;
  padding-right: 10px;
  line-height: 60px;
  height: 60px;
  // margin-bottom: 6px;
  font-size: 13px;
  &:nth-child(2) {
    color: #3f4c6b;
    // font-weight: bold;
  }
  &:nth-child(n + 3) {
    border-top: 1px solid #ebeef5;
  }
  &.border-bottom {
    border-bottom: 1px solid #ebeef5;
    word-break: break-word;
    background-color: #fafafa;
  }
  &.margin-top {
    margin-top: 6px;
  }
  &.margin-bottom {
    margin-bottom: 6px;
  }
}
.cols div:first-child:before {
  margin-top: 6px;
}

/deep/ .el-form-item__error {
  padding-top: 0;
}
</style>